const { uploadpic, getpic } = require("../services/upload.services");
const fs = require("fs");
class UploadController {
  //上传图片
  async uploadpic(ctx, next) {
    const { file } = ctx.req;
    if (!file) {
      ctx.body = {
        status: 200,
        result: {
          message: "请选择上传图片",
        },
      };
    }
    try {
      const result = await uploadpic(file);
      ctx.body = result;
    } catch (e) {
      ctx.body = e.message;
      console.log(e);
    }
  }

  //获取图片
  async getpic(ctx, next) {
    const { id } = ctx.request.params;
    const { filename, mimetype } = await getpic(id);
    const filearr = filename.split("&");
    //设置此响应头让浏览器展示图片而不是下载
    ctx.response.set("Content-Type", mimetype);
    ctx.body = fs.createReadStream(
      `./upload/${filearr[0]}/${filearr[1]}/${filename}`
    );
  }
}

module.exports = new UploadController();
